//二进制求和----67
//给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void Change(char *s)
{
    int len = strlen(s);
    for(int i = 0; i < len/2; i++)
    {
        char temp = s[i];
        s[i] = s[len - 1 -i];
        s[len - i - 1] = temp;
    }
}


char* addBinary(char* a, char* b) 
{
    Change(a);
    Change(b);
    int len = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
    int carry = 0;//进位值
    char *sum = (char *)malloc(sizeof(char) * (len+2)); //+2 一个是防止进位，一个是'\0'
    for(int i = 0; i < len; i++)
    {
        int n1 = i < strlen(a) ? a[i] - 48 : 0;//a数组的元素的值
        int n2 = i < strlen(b) ? b[i] - 48 : 0;//b数组的元素的值
        sum[i] = (n1 + n2 + carry)%2 + 48;
        carry = (n1 + n2 + carry) / 2;
    }
    if(carry != 0)//处理最开头的1位是否进位
    sum[len++] = '1';

    sum[len] = '\0';
    Change(sum);
    return sum;

}

int main()
{
    char a[] = "1010";
    char b[] = "1011";
    printf("%s\n",addBinary(a,b));
}